import numpy as np
import pandas as pd

def box_plot(df):
    q1=np.nanpercentile(df.y,25)
    q3=np.nanpercentile(df.y,75)
    iqr=q3-q1
    lower_limit = q1-1.5*iqr
    upper_limit = q3+1.5*iqr
    df['anomaly']=df.y.apply(lambda x: 1 if x<lower_limit or x>upper_limit
                             else 0)
    return df

'''
对外调用接口;
提供给外部其他Python文件调用接口.
'''
def box_plot_route(data,url):
    if url:
        data1 = pd.read_excel(url)
    else:
        data1 = data

    data1.columns = ['y']
    df1 = box_plot(data1.copy())
    label1 = np.array(df1['anomaly']).reshape(-1,1)
    label = label1.tolist()
    return label

if __name__ =="__main__":
    # 读取文件
    url = 'Box_data.xlsx'
    data = pd.read_excel('Box_data.xlsx')
    label = box_plot_route(data,url)

    # 输出label,label=0为正常点，label=1为异常点
    print('lable:', label)
